<template>
    <Card style="margin-left:-15px;margin-right:-15px;">
        <p slot="title">基本信息</p>

        <div slot="extra">
            <i-button
                v-show="showItem('access_control')"
                v-if="canUseM3Remote"
                @click="handleOpenFromRemote"
                :loading="operating">
                远程开门
            </i-button>
        </div>

        <div class="hr-device-detail">
            <Alert type="error" v-show="error">
                获取设备信息失败
                <i-button class="margin-left-10" size="small" @click="handleSearch">刷新</i-button>
            </Alert>
            <Row :gutter="40" v-show="!error" type="flex">
                <Spin v-if="loading" fix></Spin>
                <i-col span="8" class="device-info__border">
                    <h3 class="device-info__title">
                        基本信息
                        <i-button v-show="showItem" @click="handleSearch" size="small">刷新</i-button>
                    </h3>
                    <kv-wrap
                        label-width="auto"
                        fontColor="#000"
                        align="right"
                        padding="10px 0"
                        fontWeight="400"
                        fontSize="14px">
                        <kv-item label="名称:">
                            {{device.description || device.name || '无'}}
                            <i-button class="margin-left-10" size="small" type="primary" @click="handleRename(device.description || device.name)">修改</i-button>
                        </kv-item>
                        <kv-item label="序列号:">
                            {{device.sn || (device.hardware_info && device.hardware_info.sn)}}
                        </kv-item>
                        <kv-item label="uuid:">
                            {{device.uuid}}
                        </kv-item>
                        <kv-item label="状态:">
                            <span>{{device.onoff_line === 1 ? '在线' : '离线'}}</span>
                            ({{device.onoff_time | date}})
                        </kv-item>
                        <kv-item label="型号:">
                            {{device.type}}
                        </kv-item>
                        <kv-item label="绑定时间:">
                            {{device.bind_time | date}}
                        </kv-item>
                        <kv-item label="GPRS信号值:">
                            {{device.connection && device.connection.gprs_lqi}}
                        </kv-item>
                    </kv-wrap>
                </i-col>

                <i-col span="8" class="device-info__border">
                    <h3 class="device-info__title">保修信息</h3>
                    <kv-wrap
                        label-width="auto"
                        fontColor="#000"
                        align="left"
                        fontWeight="400"
                        padding="10px 0"
                        fontSize="14px">
                        <kv-item label="设备交付时间:">
                            {{device.bill_time | date}}
                        </kv-item>
                        <kv-item label="保修起始时间:">
                            {{device.guarantee_begin}}
                        </kv-item>
                        <kv-item label="保修截止时间:">
                            {{device.guarantee_end}}
                        </kv-item>
                    </kv-wrap>
                </i-col>

                <i-col span="8" v-if="device.versions">
                    <h3 class="device-info__title">硬件信息</h3>
                    <kv-wrap
                        label-width="auto"
                        fontColor="#000"
                        align="left"
                        fontWeight="400"
                        padding="10px 0"
                        fontSize="14px">
                        <kv-item
                            :label="versionMap[key] || key"
                            :key="key"
                            v-show="versionMap[key]"
                            v-for="(item,key) in device.versions">
                            {{item}}
                        </kv-item>
                    </kv-wrap>
                </i-col>
            </Row>
        </div>
    </Card>
</template>

<script>
    import { mapGetters } from 'vuex'
import debounce from 'lodash/debounce'
import { http, api } from '@/libs/http'
import { DeviceTypeEnum } from '@/libs/const'
import { refreshRoom } from '../room-list/util'
import { regexEnum } from '@/libs/validate'

/** 设备详情 */
export default{
      name: 'device-info',
      props: {
        deviceInfo: Object,
        homeId: Number
      },
      data () {
        return {
          operating: false,
          deviceId: this.deviceInfo.id,
          device: {},
          loading: false,
          error: false,
          baseRequestData: [], // roomId id 这样的请求数据
          versionMap: {
            app_version: '固件版本',
            hardware_version: '硬件版本',
            zigbee_version: 'zigbee版本'
          },
          apiMap: {
            11: api.m3_info
          }
        }
      },
      computed: {
        ...mapGetters(['canUseM3Remote'])
      },
      created () {
        const { id, room_id } = this.deviceInfo
        this.baseRequestData = [ room_id, id ]
        this.initData()
      },
      methods: {
        handleSearch: debounce(function () {
          this.initData()
        }, 200),
        async initData () {
          try {
            this.error = false
            this.loading = true
            const { room_id, id, device_type } = this.deviceInfo
            const apiModel = this.apiMap[device_type]
            const device = await http.req(apiModel, [room_id, id], null)
            if (!device) return
            if (!device.versions) device.versions = (device.hardware_info && device.hardware_info.versions) || {}
            this.device = device
          } catch (err) {
            console.log(err)
            this.error = true
          } finally {
            this.loading = false
          }
        },
        showItem (names) {
          const items = names.split(',')
          let hasItem = false
          items.forEach(item => {
            const type = DeviceTypeEnum[item.toUpperCase()]
            if (this.deviceInfo.device_type === type) hasItem = true
          })
          return hasItem
        },
        handleOpenFromRemote () {
          this.$Modal.confirm({
            loading: true,
            title: '提示',
            content: '确定进行远程开门?',
            onOk: () => {
              this.openFromRemote()
            }
          })
        },
        async openFromRemote () {
          try {
            this.operating = true
            const res = await http.req(api.m3_open, this.baseRequestData, null)
            if (res) {
              this.$Message.success('远程开门成功')
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.$Modal.remove()
            this.operating = false
          }
        },
        handleRename (name) {
          let description = name
          this.$Modal.confirm({
            title: '新名称',
            render: h => <i-input value={description} onInput={function (val) { return (description = val) }}></i-input>,
            onOk: () => {
              if (description === name) {
                this.$Modal.remove()
              } else if (!regexEnum.legalName.reg.test(description)) {
                this.$Message.info({
                  content: regexEnum.legalName.message,
                  duration: 4
                })
                this.$Modal.remove()
              } else {
                this.renameDevice(description)
              }
            },
            loading: true
          })
        },
        async renameDevice (description) {
          const { roomId, id } = this.deviceInfo
          const res = await http.req(api.device_update, [roomId, id], { description })
          this.$Modal.remove()
          if (res) {
            this.$Message.success('修改成功')
            refreshRoom(this.homeId, roomId, id, description)
            this.initData()
          }
        }
      }
    }
</script>